package com.future.mayi.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.future.mayi.R;

import java.io.File;


/**
 * H5界面的基类，所有h5调用的方法写在本类中，所有其他WebView界面均可以自动执行
 */
public abstract class BaseWebViewActivity extends BaseActivity {

    private WebView mWebView;
    public boolean needRefresh = false;
    public ProgressBar progressBar;
    private ValueCallback<Uri> mUploadMessage;
    public String appCachePath;
    private TextView tvTitle;
    protected boolean isSetTiTle = true;
    protected String tiTle = null;
    protected Bitmap icon;
    private MyWebChromeClient myWebChromeClient;
    private Handler mHandler = new Handler();

    protected Boolean isHaveTitle = true;
    private WebChromeClient.CustomViewCallback xCustomViewCallback;
    private WebSettings webSettings;

    public void initWebView(WebView webView, TextView tvTitle, ProgressBar progress_bar) {
        this.progressBar = progress_bar;
        this.tvTitle = tvTitle;
        mWebView = webView;
        webSettings = mWebView.getSettings();
        webSettings.setDomStorageEnabled(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setBuiltInZoomControls(true);
        // 排版适应屏幕
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSettings.setAppCacheMaxSize(1024 * 1024 * 8);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

        appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
        webSettings.setAppCachePath(appCachePath);
        myWebChromeClient = new MyWebChromeClient();
        mWebView.setWebChromeClient(myWebChromeClient);
        mWebView.addJavascriptInterface(this, "android");

        loadUrl("javascript:alert(injectedObject.toString())");
    }


    protected void loadUrl(String url) {
        if (!url.toLowerCase().contains("http")) {
            url = "http://".concat(url);
        }
        mWebView.loadUrl(url);
    }


    public final class MyWebChromeClient extends WebChromeClient {
        @Override
        @JavascriptInterface
        public boolean onJsAlert(WebView view, String url, String message,
                                 final JsResult result) {
            result.confirm();
            // 弹窗处理
            AlertDialog.Builder b2 = new AlertDialog.Builder(BaseWebViewActivity.this)
                    .setTitle(R.string.app_name).setMessage(message)
                    .setPositiveButton("ok", new AlertDialog.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            result.confirm();
                        }
                    });
            b2.setCancelable(false);
            b2.create();
            b2.show();
            return true;
        }


        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            BaseWebViewActivity.this.icon = icon;
            super.onReceivedIcon(view, icon);
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                    String acceptType) {
            if (mUploadMessage != null)
                return;
            mUploadMessage = uploadMsg;
        }

        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooser(uploadMsg, "");
        }

        // For Android > 4.1.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                    String acceptType, String capture) {
            openFileChooser(uploadMsg, acceptType);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            // TODO Auto-generated method stub
            if (progressBar != null)
                progressBar.setProgress(newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            // TODO Auto-generated method stub
            super.onReceivedTitle(view, title);
            if (isSetTiTle && tvTitle != null)
                tvTitle.setText(TextUtils.isEmpty(title) ? "" : title);

            tiTle = title;
            onLoadTitle(tiTle);
        }

    }

    protected abstract void onLoadTitle(String title);

    /**
     * js调用,清空历史记录
     */
    @JavascriptInterface
    public void toClear() {
        mHandler.post(new Runnable() {
            public void run() {
                try {
                    mWebView.clearHistory();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onResume() {
        try {
            if (mWebView != null) {
                mWebView.getClass().getMethod("onResume").invoke(mWebView, (Object[]) null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        super.onResume();
    }

    @Override
    public void onPause() {
        try {
            if (mWebView != null) {
                mWebView.getClass().getMethod("onPause").invoke(mWebView, (Object[]) null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        super.onPause();
    }

    @Override
    protected void onDestroy() {
        try {
            deleteDatabase("webview.db");
            deleteDatabase("webviewCache.db");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (mWebView != null) {
            mWebView = null;
        }
        if (xCustomViewCallback != null) {
            xCustomViewCallback = null;
        }
        needRefresh = false;
        super.onDestroy();
    }


    /**
     * 清理缓存 clear the cache before time numDays
     */
    private int clearCacheFolder(File dir, long numDays) {
        // WebView 缓存文件
        File appCacheDir = new File(appCachePath);
        File webviewCacheDir = new File(getCacheDir().getAbsolutePath()
                + "/webviewCache");
        // 删除webview 缓存目录
        if (webviewCacheDir.exists()) {
            deleteFile(webviewCacheDir);
        }
        // 删除webview 缓存 缓存目录
        if (appCacheDir.exists()) {
            deleteFile(appCacheDir);
        }

        int deletedFiles = 0;
        if (dir != null && dir.isDirectory()) {
            try {
                for (File child : dir.listFiles()) {
                    if (child.isDirectory()) {
                        deletedFiles += clearCacheFolder(child, numDays);
                    }
                    if (child.lastModified() < numDays) {
                        if (child.delete()) {
                            deletedFiles++;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return deletedFiles;
    }

    public void deleteFile(File file) {
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
            file.delete();
        }
    }




    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }
}
